package com.xywh.wanandroid.viewmodel

import android.util.Log
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.xywh.wanandroid.data.model.bean.ArticleItem
import com.xywh.wanandroid.data.repository.WanAndroidRepository
import com.xywh.wanandroid.event.EventViewModel
import com.xywh.wanandroid.event.EventViewModel.Companion.getUserInfoBean
import com.xywh.wanandroid.ext.requestCompose
import com.xywh.wanandroid.ext.showToastMsg
import com.xywh.wanandroid.network.apiService
import com.xywh.wanandroid.util.CacheUtil
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.ext.request
import javax.inject.Inject

@HiltViewModel
class MainComposeViewModel @Inject constructor(
    val repository: WanAndroidRepository,
    val savedStateHandle: SavedStateHandle
) : BaseViewModel() {


    private val updateData: MutableStateFlow<Int> = MutableStateFlow(0)

    init {
        viewModelScope.launch {
            updateData.collect {
//                updateData.value.plus(1)
                Log.e("updateData.value===", "${updateData.value}")
            }
        }
    }

    fun updateCollectArticleListData() {
        updateData.value = updateData.value.plus(1)
    }

    /**
     * 首页-banner列表
     * @return Flow<PagingData<BannerBean>>
     */
    val banners = repository.fetchHomeBannerList().cachedIn(viewModelScope)

    /**
     * 首页-置顶文章列表
     * @return Flow<PagingData<ArticleItem>>
     */
    val topArticles = repository.fetchHomeTopArticlesList().cachedIn(viewModelScope)

    val collectTopArticlesLiveData: Flow<PagingData<ArticleItem>> = updateData.flatMapLatest {

        repository.fetchHomeTopArticlesList()
    }.cachedIn(viewModelScope)

    /**
     * 首页-文章列表
     * @return Flow<PagingData<ArticleItem>>
     */
    val articles = repository.fetchHomeArticleList().cachedIn(viewModelScope)

    val collectArticlesLiveData: Flow<PagingData<ArticleItem>> = updateData.flatMapLatest {
        repository.fetchHomeArticleList()
    }.cachedIn(viewModelScope)

    /**
     * 广场-文章列表
     * @return Flow<PagingData<ArticleItem>>
     */
    val squareArticles = repository.fetchSquareArticleList().cachedIn(viewModelScope)

    val collectSquareArticlesLiveData: Flow<PagingData<ArticleItem>> = updateData.flatMapLatest {
        repository.fetchSquareArticleList()
    }.cachedIn(viewModelScope)

    /**
     * 公众号-列表
     * @return Flow<PagingData<WXChapterItem>>
     */
    val wxChapters = repository.fetchWXChaptersList().cachedIn(viewModelScope)


    var wechatArticle: MutableState<Flow<PagingData<ArticleItem>>?> = mutableStateOf(null)

    var wxChapterId = 0

    /**
     * 公众号-文章列表
     * @param wxChapterId Int 公众号id
     * @return Flow<PagingData<ArticleItem>>
     */

    fun getWechatArticle(): Flow<String> {
        wechatArticle.value =
            repository.fetchWechatArticleList(wxChapterId).cachedIn(viewModelScope)
        return flow { "" }
    }

    val collectWechatArticleLiveData = updateData.flatMapLatest {

        getWechatArticle()
    }

    /**
     * 体系-体系列表
     * @return Flow<PagingData<KnowledgeTreeItem>>
     */
    val knowledgeTree = repository.fetchKnowledgeTreeList().cachedIn(viewModelScope)

    /**
     * 体系-导航列表
     * @return Flow<PagingData<NavigationBeanItem>>
     */
    val navigationList = repository.fetchNavigationList().cachedIn(viewModelScope)


    /**
     * 项目-分类列表
     * @return Flow<PagingData<ProjectTreeItem>>
     */
    val projectTree = repository.fetchProjectTreeList().cachedIn(viewModelScope)


    var projectArticles: MutableState<Flow<PagingData<ArticleItem>>?> = mutableStateOf(null)

    var projectId = 0

    /**
     * 项目-文章列表
     * @param projectId Int 项目id
     * @return Flow<PagingData<ArticleItem>>
     */

    fun getProjectArticles(): Flow<String> {
        projectArticles.value =
            repository.fetchProjectArticleList(projectId).cachedIn(viewModelScope)
        return flow { "" }
    }

    val collectProjectArticlesLiveData = updateData.flatMapLatest {
        getProjectArticles()
    }

    fun getUserInfo() {
        request({ apiService.getUserInfo() }, {
            getUserInfoBean.value = true
            CacheUtil.setUserInfoBean(it)
        })
    }

    /**
     * 退出
     */

    fun logout(updateMainScreenCollectListData: () -> Unit) {
        requestCompose(
            { apiService.logout() }, {
                showToastMsg("退出成功")
                EventViewModel.isLogin.value = false
                CacheUtil.setUser(null)
                updateMainScreenCollectListData.invoke()
            }, {
                showToastMsg(it.errorMsg)
            }, true, "退出中..."
        )
    }

    /**
     * 添加收藏
     * @param id Int
     */
    fun addCollectArticle(id: Int) {
        requestCompose(
            { apiService.addCollectArticle(id) },
            {

                showToastMsg("收藏成功")
            }, {
                showToastMsg(it.errorMsg)
            },
            true,
            "收藏中..."
        )
    }

    /**
     * 取消收藏
     * @param id Int
     */
    fun cancelCollectArticle(id: Int) {
        requestCompose(
            { apiService.cancelCollectArticle(id) },
            {
                showToastMsg("取消收藏成功")
            }, {
                showToastMsg(it.errorMsg)
            },
            true,
            "取消收藏中..."
        )
    }

}
